﻿using ERPPublic;
using MediatR;
using Newtonsoft.Json;
using ProcurementManagement.Applcation.Command.PurchaseRefundCommand;
using ProcurementManagement.Domain.Dtos;
using ProcurementManagement.Domain.ProcurementDomain;
using ProcurementManagement.Dtos;
using SqlSugar;
using static ERPPublic.ParseAPI;

namespace ProcurementManagement.Applcation.CommandHanlers.PurchaseRefundCommandHandler
{
    /// <summary>
    /// 应退采购款列表中介者
    /// </summary>
    public class GetPurchaseRefundCommandHandler:IRequestHandler<GetPurchaseRefundCommand, PageDto<GetPurchaseRefundDto>>
    {
        ISqlSugarClient db;

        public GetPurchaseRefundCommandHandler(ISqlSugarClient db)
        {
            this.db = db;
        }
        public async Task<PageDto<GetPurchaseRefundDto>> Handle(GetPurchaseRefundCommand request, CancellationToken cancellationToken)
        {
            List<Products> products = await GetProductList("", "", 1, 1000);

            var vendorData = db.Queryable<Vendor>()
                .InnerJoin<PurchaseReturns>((v, pr) => v.VName == pr.VName)
                .InnerJoin<ReturnProduct>((v, pr, rp) => pr.PurchaseReturnsCode == rp.PurchaseReturnsCode)
                .Where((v, pr, rp) => v.IsDel == false && pr.PurchaseReturnsCode == rp.PurchaseReturnsCode)
                .Select((v, pr, rp) => new GetPurchaseRefundDto
                {
                    RefundAmoun = pr.RefundAmoun,
                    PRtotalAmount = pr.PRtotalAmount,
                    VName = v.VName,
                    PurchaseReturnsIds = pr.PurchaseReturnsIds,
                    PurchaseReturnsCode = pr.PurchaseReturnsCode,
                    PurchaseReturnsTopic = pr.PurchaseReturnsTopic,
                    PReturnsPersonnel = pr.PReturnsPersonnel,
                    ManpowerId = pr.ManpowerId,
                    PRReturnDate = pr.PRReturnDate,
                    PROutboundProgress = pr.PROutboundProgress,
                    PRShipmentState = pr.PRShipmentState,
                    PRReturnType = pr.PRReturnType,
                    RPNum = rp.RPNum,
                    RPPrice = rp.RPPrice,
                    ProductId = rp.ProductId,
                    VendorId = v.VendorId,
                    AddTime=pr.AddTime
                }).ToList();

            // 3. 在内存中进行联接
            var list = (from dbData in vendorData
                        join product in products on dbData.ProductId equals product.ProductId
                        select new GetPurchaseRefundDto
                        {
                            RefundAmoun = dbData.RefundAmoun,
                            PRtotalAmount = dbData.PRtotalAmount,
                            VName = dbData.VName,
                            PurchaseReturnsIds = dbData.PurchaseReturnsIds,
                            PurchaseReturnsCode = dbData.PurchaseReturnsCode,
                            PurchaseReturnsTopic = dbData.PurchaseReturnsTopic,
                            PReturnsPersonnel = dbData.PReturnsPersonnel,
                            ManpowerId = dbData.ManpowerId,
                            PRReturnDate = dbData.PRReturnDate,
                            PROutboundProgress = dbData.PROutboundProgress,
                            PRShipmentState = dbData.PRShipmentState,
                            PRReturnType = dbData.PRReturnType,
                            RPNum = dbData.RPNum,
                            RPPrice = dbData.RPPrice,
                            ProductId = dbData.ProductId,
                            VendorId = dbData.VendorId,
                            PNumber = product.PNumber,
                            PName = product.PName,
                            PSpec = product.PSpec,
                            PUnit = product.PUnit,
                            AddTime=dbData.AddTime
                        });
            list = list.GroupBy(x => x.PurchaseReturnsIds).Select(x => new GetPurchaseRefundDto
            {
                RefundAmoun = x.First().RefundAmoun,
                VName = x.First().VName,
                PRtotalAmount=x.First().PRtotalAmount,
                PurchaseReturnsIds = x.First().PurchaseReturnsIds,
                PurchaseReturnsCode = x.First().PurchaseReturnsCode,
                PurchaseReturnsTopic = x.First().PurchaseReturnsTopic,
                PReturnsPersonnel = x.First().PReturnsPersonnel,
                ManpowerId = x.First().ManpowerId,
                PRReturnDate = x.First().PRReturnDate,
                PROutboundProgress = x.First().PROutboundProgress,
                PRShipmentState = x.First().PRShipmentState,
                PRReturnType = x.First().PRReturnType,
                RPNum = x.First().RPNum,
                RPPrice = x.Sum(x=>x.RPPrice),
                ProductId = x.First().ProductId,
                VendorId = x.First().VendorId,
                PNumber = x.First().PNumber,
                PName = x.First().PName,
                PSpec = x.First().PSpec,
                PUnit = x.First().PUnit,
                AddTime = x.First().AddTime
            }).ToList();
            if (request.KPrice != null)
            {
                list = list.Where(x => x.RPPrice >= request.KPrice).ToList();
            }
            if (request.SPrice != null)
            {
                list = list.Where(x => x.RPPrice <= request.SPrice).ToList();
            }
            if (!string.IsNullOrEmpty(request.VName))
            {
                list = list.Where(x => x.VName == request.VName).ToList();
            }
            if (!string.IsNullOrEmpty(request.KDate))
            {
                list = list.Where(x => x.AddTime >=Convert.ToDateTime(request.KDate)).ToList();
            }
            if (!string.IsNullOrEmpty(request.SDate))
            {
                list = list.Where(x => x.AddTime <= Convert.ToDateTime(request.SDate)).ToList();
            }
            if (!string.IsNullOrEmpty(request.PReturnsPersonnel))
            {
                list = list.Where(x => x.PReturnsPersonnel == request.PReturnsPersonnel).ToList();
            }
            if (request.PRtotalAmount != null)
            {
                list = list.Where(x => x.PRtotalAmount >= request.PRtotalAmount).ToList();
            }
            if (request.SPRtotalAmount != null)
            {
                list = list.Where(x => x.PRtotalAmount <= request.SPRtotalAmount).ToList();
            }
            if (request.PROutboundProgress != null)
            {
                list = list.Where(x => x.PROutboundProgress == request.PROutboundProgress).ToList();
            }
            if (!string.IsNullOrEmpty(request.KPRReturnDate))
            {
                list = list.Where(x => x.PRReturnDate >= Convert.ToDateTime(request.KPRReturnDate)).ToList();
            }
            if (!string.IsNullOrEmpty(request.SPRReturnDate))
            {
                list = list.Where(x => x.PRReturnDate <= Convert.ToDateTime(request.SPRReturnDate)).ToList();
            }
            if (!string.IsNullOrEmpty(request.PRDocumentNumber))
            {
                list = list.Where(x => x.PRDocumentNumber == request.PRDocumentNumber).ToList();
            }
            if (!string.IsNullOrEmpty(request.PurchaseReturnsTopic))
            {
                list = list.Where(x => x.PurchaseReturnsTopic.Contains(request.PurchaseReturnsTopic)).ToList();
            }
            PageDto<GetPurchaseRefundDto> page = new PageDto<GetPurchaseRefundDto>();
            page.lcount = list.Count();
            page.pcount = (int)Math.Ceiling(page.lcount * 1.0 / request.Psize);
            page.list = list.OrderByDescending(x => x.ManpowerId).Skip((request.Pindex - 1) * request.Psize).Take(request.Psize).ToList();

            return page;



        }

        /// <summary>
        /// 显示产品信息
        /// </summary>
        /// <param name="PName"></param>
        /// <param name="PNumber"></param>
        /// <param name="pindex"></param>
        /// <param name="psize"></param>
        /// <returns></returns>
        public async Task<dynamic> GetProductList(string? PName, string? PNumber, int pindex, int psize)
        {
            string token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI1MCIsInNpZCI6IjE4NjcwOTU3MzQ0NjIwNTg0OTYiLCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL2dyb3Vwc2lkIjoiMTksMTkiLCJqdGkiOiI1MGYyMWRmZS0yNWQ3LTQ1OTQtOTg1Yi0wZTM2MDhhZjJiNmYiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoi5LuY5rSb5ZiJIiwiaHR0cDovL3NjaGVtYXMueG1sc29hcC5vcmcvd3MvMjAwNS8wNS9pZGVudGl0eS9jbGFpbXMvdXJpIjoiLyIsImlzcyI6IlJlbmFvYm8yMDA0IiwiYXVkIjoiV2VpZnV3dTIyMDNBIn0._wh23n1M7asMGST9NyeZj-5rk5ICAiOFv6yDk6e2o7Y";
            HttpClientWrapper cilent = new HttpClientWrapper(token);

            string chanpin = "http://116.205.121.197:8000/erpcp/api/Product/ProductShow?PName=" + PName + "&PNumber=" + PNumber + "&ProductTypeId=" + 0 + "&PageIndex=" + pindex + "&PageSize=" + psize;

            string postReponse = await cilent.GetAsync(chanpin);
            var json = JsonConvert.DeserializeObject<ApiResultList<Products>>(postReponse);
            return json.data.list;
        }
        //产品
        public class Products
        {
            /// <summary>
            /// 产品Id
            /// </summary>
            [SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
            public int ProductId { get; set; }
            /// <summary>
            /// 标识
            /// </summary>

            public int? PCharacteristic { get; set; }
            /// <summary>
            /// 产品编号
            /// </summary>
            [SugarColumn(ColumnDataType = "Nvarchar(50)")]//设计长度
            public string? PNumber { get; set; }
            /// <summary>
            /// 产品名称
            /// </summary>
            /// 
            [SugarColumn(ColumnDataType = "Nvarchar(50)")]//设计长度
            public string? PName { get; set; }
            /// <summary>
            /// 规格型号
            /// </summary>
            /// 
            [SugarColumn(ColumnDataType = "Nvarchar(50)")]//设计长度
            public string? PSpec { get; set; }
            /// <summary>
            /// 单位
            /// </summary>
            /// 
            [SugarColumn(ColumnDataType = "Nvarchar(50)")]//设计长度
            public string? PUnit { get; set; }

            /// <summary>
            /// 产品分类ID
            /// </summary>

            public int ProductTypeId { get; set; }




        }









    }
}
